<template>
  <div class="loginBox">
    <h3>GameWorld 管理平台</h3>
    <el-form class="loginForm" @submit.prevent="login" label-width="80px">
      <el-form-item label="账户:" label-position="right">
        <el-input
          type="text"
          v-model="account"
          placeholder="请输入账户"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码:" label-position="right">
        <el-input
          type="password"
          show-password
          v-model="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" style="width: 100%">
          登录
        </el-button>
      </el-form-item>
      <el-form-item>
        <slot default></slot>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { loginApi } from "@/apis/user";
import { useTokenStore } from "@/store/user";
import router from "@/router";
import { ElLoading, ElMessage, ElNotification } from "element-plus";

const tokenStore = useTokenStore();
const account = ref("");
const password = ref("");
const formData = new FormData();

// 用户登录
async function login() {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  formData.append("account", account.value);
  formData.append("password", password.value);
  try {
    const res = await loginApi(formData);
    tokenStore.setToken(res.data);
    if (tokenStore.token) {
      await router.push("/");
      ElMessage.success("登录成功！");
      ElNotification({
        title: "登录成功",
        message: "Game World 管理平台欢迎您！",
        type: "success",
        duration: 3000,
        offset: 100,
      });
    } else {
      formData.delete("account");
      formData.delete("password");
      ElMessage.error("登录失败，请检查账户和密码！");
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.close();
  }
}
</script>

<style scoped>
.loginBox {
  padding: 0.7em 1em;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loginForm {
  margin-top: 1em;
  max-width: 100%;
}
</style>
